package com.linxin.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linxin.reggie.common.Result;
import com.linxin.reggie.entity.Category;
import com.linxin.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Category 分类管理(菜品 套餐分类)
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody Category category) {
        log.info("新添加的分类为: {}", category);
        categoryService.save(category);

        return Result.success("新增分类成功");
    }

    /**
     * 分页展示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize) {
        log.info("分类 page = {}, pageSize = {}", page, pageSize);

        // 分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);

        // 条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 添加排序
        queryWrapper.orderByAsc(Category::getSort);

        // 传给service层, 进行分页查询
        categoryService.page(pageInfo, queryWrapper);

        // 响应前端
        return Result.success(pageInfo);
    }

    /**
     * 删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(Long ids) {
        log.info("需要删除的分类id为 {}", ids);

        // 判断分类是否关联菜品和套餐, 有关联则不能删除
        // 在service层新增删除方法
        // categoryService.removeById(ids);

        // 调用新的删除方法
        categoryService.remove(ids);
        return Result.success("删除分类成功");
    }

    @PutMapping
    public Result<String> update(@RequestBody Category category) {
        log.info("修改的数据为: {}", category);

        // service层修改
        categoryService.updateById(category);

        return Result.success("修改分类成功");
    }

    /**
     * 根据类型查询category(新增菜品页面)
     * @param category 用于接收传入的type
     * @return
     */
    @GetMapping("/list")
    public Result<List<Category>> list(Category category) {
        // 条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        // 条件条件, 判断是否为空
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());

        // 添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        // 查询
        List<Category> list = categoryService.list(queryWrapper);

        // 返回结果
        return Result.success(list);
    }
}
